package xyz.renyumeng.xkm.user.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.builder.GenericBuilder;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.renyumeng.xkm.exception.XkmException;
import xyz.renyumeng.xkm.model.user.UserInfo;
import xyz.renyumeng.xkm.result.Result;
import xyz.renyumeng.xkm.user.dto.UserInfoDto;
import xyz.renyumeng.xkm.user.dto.UserLoginDto;
import xyz.renyumeng.xkm.user.dto.UserLoginParam;
import xyz.renyumeng.xkm.user.mapper.UserInfoMapper;
import xyz.renyumeng.xkm.user.service.UserLoginService;


/**
 * @author renyumeng
 * @date Created in 16:48 2023/7/5
 */

@Service
@Transactional
public class UserLoginServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserLoginService {
    @Override
    public Result<UserLoginDto> login(UserLoginParam userLoginParam) {
        // 判断用户是否存在，不存在则提示用户注册
        String username = userLoginParam.getUsername();
        LambdaQueryWrapper<UserInfo> queryWrapperByUsername = new LambdaQueryWrapper<>();
        queryWrapperByUsername.eq(UserInfo::getUsername, username);
        UserInfo user = this.getOne(queryWrapperByUsername);
        if (ObjectUtil.isEmpty(user)) {
            Result<UserLoginDto> result = new Result<>();
            result.setCode(201);
            result.setMessage("不存在该用户,请先注册!");
            result.setData(null);
            return result;
        }

        StpUtil.login(user.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String tokenValue = tokenInfo.getTokenValue();

        UserLoginDto userLoginDto = new UserLoginDto();
        userLoginDto.setUserId(user.getId());
        userLoginDto.setToken(tokenValue);
        return Result.ok(userLoginDto).message("登录成功!");
    }

    @Override
    public Result<?> logout(Long userId, String satoken) {
        if (!ObjectUtil.isEmpty(userId)) {
            StpUtil.logout(userId);
        } else if (StrUtil.isNotBlank(satoken)) {
            StpUtil.logoutByTokenValue(satoken);
        }
        return Result.ok(null).message("退出登录成功!");
    }

    @Override
    public Result<?> register(UserLoginParam userLoginParam) {
        String username = userLoginParam.getUsername();
        String password = userLoginParam.getPassword();
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUsername, username);

        UserInfo existUserInfo = this.getOne(queryWrapper);

        if (!ObjectUtil.isEmpty(existUserInfo)) {
            return Result.ok(null).message("该用户已经存在!").code(201);
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setPassword(password);
        String id = IdUtil.randomUUID();
        String nickName = "用户" + id;
        userInfo.setNickname(nickName);
        userInfo.setCreditScore(100);
        this.save(userInfo);
        return Result.ok(null).message("创建用户成功!");
    }

    @Override
    public Result<?> editUserInfo(UserInfoDto userInfoDto) {
        String satoken = userInfoDto.getSatoken();
        Object userIdObject = StpUtil.getLoginIdByToken(satoken);
        Long userId = Convert.toLong(userIdObject);

        UserInfo userInfo = BeanUtil.copyProperties(userInfoDto, UserInfo.class);
        userInfo.setId(userId);
        boolean isUpdated = this.updateById(userInfo);
        if (!isUpdated) {
            throw new XkmException(201, "修改用户信息失败!");
        }
        return Result.ok(null).message("修改用户信息成功!");
    }

    @Override
    public Result<UserInfo> getUserInfoByUserId(Long userId) {
        UserInfo userInfo = this.getById(userId);
        if (ObjectUtil.isEmpty(userInfo)) {
            throw new XkmException(201, "用户信息不存在!");
        }
        return Result.ok(userInfo).message("获取用户信息成功!");
    }
}
